import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QDialog, QLabel, QHBoxLayout, QLineEdit, QFormLayout

from PyQt5.Qt import QDialog

from config.config import Config
from ui.py_ui.ui_leaf_node_form import UiNodeLeafForm

from resources.statics import resources_rc
from views.set_css import set_css


class LeafNodeFormWindow(QDialog, UiNodeLeafForm):

    def __init__(self, node=None):
        super().__init__()
        self.setupUi(self)
        self.node = node
        self.math_widget.setStyleSheet(
            self.node.leaf_info.math_widget
        )
        self.info_image_widget.setStyleSheet(
            self.node.leaf_info.info_image_widget
        )
        self.add_tool_button.setIcon(QIcon(os.path.join(Config.svg_path, "plus.svg")))
        self.sub_tool_button.setIcon(QIcon(os.path.join(Config.svg_path, "minus.svg")))

        for item in self.node.leaf_info.params:
            self.add_tool_button_clicked(item.get("key"), item.get("message"))

        # self.add_tool_button.clicked.connect(lambda: self.add_tool_button_clicked(text="新标签", text_label="这是一个新标签"))
        # self.sub_tool_button.clicked.connect(self.sub_tool_button_clicked)
        set_css(self, os.path.join(Config.static_path, 'form_leaf_edit.css'))

        # 动态改变文本及图片
        self.change_item_content(self.text_label, self.node.leaf_info.label_text)
        self.change_item_content(self.label, self.node.leaf_info.math_label_text)

    def add_tool_button_clicked(self, text, text_label=None):
        label = QLabel(text)
        label.setStyleSheet(
            "border: 0px solid gray;border-radius: "
            "5px;padding: 10px;margin-top: 20px;margin-bottom: 20px;margin-right: 50px;")
        line_edit = QLineEdit()
        line_edit.setStyleSheet("border: 0px solid gray;border-radius: 10px;"
                                "padding: 10px;font-family: Arial, Helvetica, sans-serif;"
                                "margin-top: 20px;margin-bottom: 20px;")
        label.setToolTip(text_label)
        self.formLayout.addRow(label, line_edit)

    def sub_tool_button_clicked(self):
        for i in range(self.formLayout.rowCount()):
            item = self.formLayout.itemAt(i, QFormLayout.FieldRole)
            if item and isinstance(item.widget(), QLineEdit) and item.widget().hasFocus():
                self.formLayout.removeRow(i)
                break

    def change_item_content(self, item, content):
        item.setText(content)


if __name__ == '__main__':
    app = QApplication([])
    # set_css(app, os.path.join(Config.static_path, 'form_line_edit.css'))
    stats = LeafNodeFormWindow()
    # apply_stylesheet(app, theme='dark_teal.xml')
    stats.show()
    app.exec_()
